package com.jack.payment.util.network;

import cn.hutool.core.io.resource.ClassPathResource;
import com.jack.payment.util.common.StringUtil;
import org.lionsoul.ip2region.xdb.Searcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class IP2RegionUtil {
    private static Logger log = LoggerFactory.getLogger(IP2RegionUtil.class);

    private static Searcher SEARCHER;

    private static String[] privateNetWorkRanges = {
            "10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}",
            "172\\.(1[6-9]|2\\d|3[01])\\.\\d{1,3}\\.\\d{1,3}",
            "192\\.168\\.\\d{1,3}\\.\\d{1,3}"
    };


    static {
        ClassPathResource resource = new ClassPathResource(
                "ip2region.xdb"
        );
        try {
            byte[] ip_db = Searcher.loadContentFromFile(resource.getFile().getAbsolutePath());
            SEARCHER = Searcher.newWithBuffer(ip_db);
        } catch (IOException e) {
            log.error("加载ip2location bin文件失败");
        }
    }


    public static String getAppointIpRegion(String ip){
        if (StringUtil.isEmpty(ip)) {
            return "未知";
        }
        // 检查是否是本地地址
        if ("127.0.0.1".equals(ip) || "localhost".equalsIgnoreCase(ip)) {
            return "未知";
        }
        for (String range  : privateNetWorkRanges) {
            if (ip.matches(range )) {
                return "未知";
            }
        }
        String region = null;
        try {
            region = SEARCHER.search(ip);
        } catch (Exception e) {
            log.error("未在ip数据库中匹配到合适的ip地址, {}", ip);
            return "未知";
        }
        String withoutLastPipe = region.replace("|0", "");
        region = withoutLastPipe.replace("|", "-");
        return region;
    }
}
